package com.mainbo.modular.system.controller;

import cn.stylefeng.roses.core.base.controller.BaseController;
import com.alibaba.druid.sql.dialect.oracle.ast.stmt.OracleCreateTableStatement;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.mainbo.core.shiro.SessionKey;
import com.mainbo.core.shiro.ShiroKit;
import com.mainbo.core.util.Result;
import com.mainbo.modular.jms.JmsService;
import com.mainbo.modular.jms.MessageTypes;
import com.mainbo.modular.jms.model.SectionUnionMessageVo;
import com.mainbo.modular.system.model.PtOrg;
import com.mainbo.modular.system.model.PtSectionTime;
import com.mainbo.modular.system.model.PtSectionUnion;
import com.mainbo.modular.system.model.meta.ConfigConstants;
import com.mainbo.modular.system.model.meta.MetaUtils;
import com.mainbo.modular.system.model.meta.vo.Meta;
import com.mainbo.modular.system.model.vo.SchoolYearVo;
import com.mainbo.modular.system.service.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.beans.factory.annotation.Autowired;
import com.mainbo.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;
import com.mainbo.modular.system.model.PtSectionCategory;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 节次管理控制器
 *
 * @author fengshuonan
 * @Date 2020-03-10 15:07:50
 */
@Controller
@RequestMapping("/ptSectionCategory")
public class PtSectionCategoryController extends BaseController {
    private static final Logger logger= LoggerFactory.getLogger(PtSectionCategoryController.class);

    private String PREFIX = "/system/ptSectionCategory/";

    @Autowired
    private IPtSectionCategoryService ptSectionCategoryService;
    @Resource
    private IPtOrgService orgService;
    @Resource
    private IPtSchoolYearTermManageService schoolYearTermManageService;
    @Resource
    private IPtSectionUnionService ptSectionUnionService;
    @Resource
    private IPtSectionTimeService ptSectionTimeService;
    @Resource
    private JmsService jmsService;

    /**
     * 跳转到节次管理首页
     */
    @RequestMapping("")
    public String index(Model model) {

        PtOrg org= ShiroKit.getSessionAttr(SessionKey.CURRENT_ORG);
        if ((org == null)) {
            model.addAttribute("orgId","0");
            model.addAttribute("areaId",0);
            return PREFIX + "ptSectionCategory_org.html";
        }
        model.addAttribute("orgId",org.getId());
        model.addAttribute("areaId",org.getAreaId());
        return PREFIX + "ptSectionCategory_list.html";
    }

    /**
     * 跳转到添加节次管理
     */
    @RequestMapping("/ptSectionCategory_add")
    public String ptSectionCategoryAdd(Model m, String orgId) {
        PtOrg org = orgService.selectById(orgId);
        if (null != org) {

            List<Meta> schoolYear = schoolYearTermManageService.getSchoolYear(orgId);
            if(CollectionUtils.isEmpty(schoolYear)){
                logger.error("请先设置学年");
            }
            final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy.MM.dd");
            String yearId = "";
            Meta mt = null;
            String start = "";
            String end = "";
            for (Meta meta:schoolYear
            ) {
                String value = meta.getValue();
                String[] split = value.split("-");
                start = split[0];
                end = split[1];
                long startTime = 0;
                long endTime = 0;
                try {
                    startTime = dateFormat.parse(start).getTime();
                    endTime = dateFormat.parse(end).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                long now = new Date().getTime();
                if(now>startTime &&(now<endTime)){
                    yearId = String.valueOf(meta.getId());
                    mt = meta;
                    break;
                }
            }
            if(null==mt){
                return PREFIX+"no_schoolTerm.html";
            }
            List<SchoolYearVo> yearAndTerm = schoolYearTermManageService.getSchoolYearAndTermByOrg(orgId);
            List<SchoolYearVo> schoolTerm = schoolYearTermManageService.getSchoolTerm(mt.getId());
            Collections.sort(schoolTerm, new Comparator<SchoolYearVo>() {
                @Override
                public int compare(SchoolYearVo o1, SchoolYearVo o2) {
                    try {
                        int diff = (int) (dateFormat.parse(o1.getTermStartTime()).getTime() - dateFormat.parse(o2.getTermEndTime()).getTime());
                        if(diff>0){
                            return 1;
                        }else if (diff<0){
                            return -1;
                        }
                        return 0;
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    return 0;
                }
            });
            m.addAttribute("schoolTerm",schoolTerm);
            m.addAttribute("start",start);
            m.addAttribute("end",end);
            m.addAttribute("year",mt);
            m.addAttribute("yearAndTerm",yearAndTerm);
            m.addAttribute("metaList", MetaUtils.listMeta(ConfigConstants.WEEK));
            m.addAttribute("org", org);
            m.addAttribute("sectionCount",getCount());

        }
        return PREFIX + "ptSectionCategory_add.html";
    }


    private  List<Integer> getCount(){
        List<Integer> list=new ArrayList<>();
        for (int i=4;i<16;i++){
            list.add(i);
        }
        return list;
    }

    /**
     * 跳转到修改节次管理
     */
    @RequestMapping("/ptSectionCategory_update/{ptSectionCategoryId}")
    public String ptSectionCategoryUpdate(@PathVariable String  ptSectionCategoryId, Model model) {
        PtSectionCategory ptSectionCategory = ptSectionCategoryService.selectById(ptSectionCategoryId);
        PtOrg org = orgService.selectById(ptSectionCategory.getOrgId());
        EntityWrapper<PtSectionTime> st = new EntityWrapper<>();
        st.eq("section_category_id",ptSectionCategoryId);
       st.orderBy("start_time",true);
        List<PtSectionTime> stList = ptSectionTimeService.selectList(st);
        SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        String startTime = format.format(ptSectionCategory.getStartTime());
        String endTime = format.format(ptSectionCategory.getEndTime());
        String week = ptSectionCategory.getWeek();
        String[] weekArr = week.split(",");
        List<String> weekList = Arrays.asList(weekArr);


        List<Meta> schoolYear = schoolYearTermManageService.getSchoolYear(ptSectionCategory.getOrgId());
        String yearId = "";
        Meta mt = null;
        String start = "";
        String end = "";
        for (Meta meta:schoolYear
        ) {
            String value = meta.getValue();
            String[] split = value.split("-");
            start = split[0];
            end = split[1];
            long sTime = 0;
            long eTime = 0;
            try {
                sTime = format.parse(start).getTime();
                eTime = format.parse(end).getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            long now = new Date().getTime();
            if(now>sTime && now<eTime){
                yearId = String.valueOf(meta.getId());
                mt = meta;
                break;
            }
        }
        List<SchoolYearVo> yearAndTerm = schoolYearTermManageService.getSchoolYearAndTermByOrg(ptSectionCategory.getOrgId());
        List<SchoolYearVo> schoolTerm = schoolYearTermManageService.getSchoolTerm(mt.getId());
        model.addAttribute("org", org);
        model.addAttribute("schoolTerm",schoolTerm);
        model.addAttribute("year",mt);
        model.addAttribute("weekList",weekList);
        model.addAttribute("startTime", startTime);
        model.addAttribute("endTime",endTime);
        model.addAttribute("start",start);
        model.addAttribute("end",end);
        model.addAttribute("item", ptSectionCategory);
        model.addAttribute("stList", stList);
        model.addAttribute("metaList", MetaUtils.listMeta(ConfigConstants.WEEK));
        model.addAttribute("sectionCount",getCount());
        LogObjectHolder.me().set(ptSectionCategory);
        return PREFIX + "ptSectionCategory_edit.html";
    }

    /**
     * 获取节次管理列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String orgId) {
        EntityWrapper<PtSectionCategory> sc = new EntityWrapper<>();
        sc.eq("deleted",0);
        sc.eq("org_id",orgId);
        sc.orderBy("create_time",false);
       List<PtSectionCategory> list=ptSectionCategoryService.selectList(sc);
        SimpleDateFormat dateFormat = new SimpleDateFormat(
                "yyyy.MM.dd");
       for (PtSectionCategory ptSectionCategory:list){
           if (ptSectionCategory.getEndTime()!=null&& ptSectionCategory.getStartTime()!=null){
               String start=dateFormat.format(ptSectionCategory.getStartTime());
               String end=dateFormat.format(ptSectionCategory.getEndTime());
               ptSectionCategory.setUseTime(start.concat("-").concat(end));
           }

       }
           return list;
    }

    /**
     * 新增节次管理
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Result add(PtSectionUnion ptSectionUnion, Integer sections) {
        Result result = new Result();
        try {
            if (ptSectionUnion.getTermId()==null){
                result.setCode(Result.FAIL);
                result.setMsg("请选择学学期");
                return result;
            }
            //保存之前先验证时间有无重叠
            EntityWrapper<PtSectionCategory> wrapper = new EntityWrapper<>();
            wrapper.eq("org_id",ptSectionUnion.getOrgId());
            wrapper.eq("deleted",0);
            List<PtSectionCategory> all = ptSectionCategoryService.selectList(wrapper);
            for (PtSectionCategory section:all) {

                //如果新保存得节次得开始时间在之前已有节次得开始结束时间之内,
                //或新保存得节次得结束时间在之前已有节次得开始结束时间之内
                if(((ptSectionUnion.getStartTime().compareTo(section.getStartTime()))!=1
                        && (ptSectionUnion.getEndTime().compareTo(section.getStartTime()))==1)
                        || ((ptSectionUnion.getStartTime().compareTo(section.getEndTime()))!=1
                        && (ptSectionUnion.getEndTime().compareTo(section.getEndTime()))==1 )){

                    result.setCode(Result.FAIL);
                    result.setMsg("与已有节次得应用时间重叠");
                    return result;
                }
            }

            Date beginTime = new Date();
            ptSectionUnion.setDeleted(0);
            String[] gradeArr = new String[0];
            String[] weekArr = new String[0];
            String[] stStartArr = new String[0];
            String[] stEndArr = new String[0];
            ArrayList<PtSectionUnion> secList = new ArrayList<>();
            String stStartTime = ptSectionUnion.getStStartTime();
            String stEndTime = ptSectionUnion.getStEndTime();


            if (StringUtils.isNotBlank(stStartTime) && StringUtils.isNotBlank(stEndTime)) {
                stStartArr = stStartTime.split(",");
                stEndArr = stEndTime.split(",");
                //根据开始时间给数组进行排序·
                Arrays.sort(stStartArr);
                Arrays.sort(stEndArr);
            }
            if(StringUtils.isNotBlank(ptSectionUnion.getOrgId())){
                PtOrg org = orgService.selectById(ptSectionUnion.getOrgId());
                ptSectionUnion.setOrgName(org.getName());
                String termName = MetaUtils.getMeta(Integer.valueOf(ptSectionUnion.getTermId())).getName();
                if(StringUtils.isNotBlank(termName)){
                    if(termName.equals("上学期") || termName.equals("下学期")){
                        ptSectionUnion.setTermName(termName);
                    }else{
                        ptSectionUnion.setTermName("全学年");
                    }
                }
            }
            ptSectionUnion.setCreateTime(new Date());
            PtSectionCategory sc = new PtSectionCategory();
            PtSectionTime st = new PtSectionTime();
            BeanUtils.copyProperties(ptSectionUnion, sc);
            BeanUtils.copyProperties(ptSectionUnion, st, "name");
            sc.setCreator(ShiroKit.getUser().getId());
            sc.setSections(sections);
            sc.setDeleted(0);
            sc.setEnable(1);
             ptSectionCategoryService.insert(sc);
            ArrayList<PtSectionTime> stList = new ArrayList<>();

            for (int i = 0; i < stStartArr.length; i++) {
                PtSectionTime sect = new PtSectionTime();
                BeanUtils.copyProperties(ptSectionUnion, sect);
                sect.setName("第" + (i + 1) + "节");
                sect.setSection(i + 1);
                sect.setStartTime(stStartArr[i]);
                sect.setEndTime(stEndArr[i]);
                sect.setSectionCategoryId(sc.getId());
                stList.add(sect);
            }
            ptSectionTimeService.insertBatch(stList);

            //保存细节表


                /*if (StringUtils.isNotBlank(su.getGradeId())) {
                    gradeArr = su.getGradeId().split(",");*/
            if (StringUtils.isNotBlank(ptSectionUnion.getWeek())) {
                weekArr = ptSectionUnion.getWeek().split(",");
                        /*for (int i = 0; i < gradeArr.length; i++) {
                            SectionUnion sec = new SectionUnion();
                            BeanUtils.copyProperties(su, sec, "id");
                            sec.setGradeId(gradeArr[i]);*/
                for (int j = 0; j < weekArr.length; j++) {
                    PtSectionUnion sec2 = new PtSectionUnion();
                    BeanUtils.copyProperties(ptSectionUnion, sec2, "id");
                    sec2.setWeek(weekArr[j]);
                    for (int k = 0; k < stStartArr.length; k++) {
                        PtSectionUnion sec3 = new PtSectionUnion();
                        BeanUtils.copyProperties(sec2, sec3, "id");
                        sec3.setCategoryId(sc.getId());
                        /*sec3.setGradeName(MetaUtils.getMeta(Integer.valueOf(sec.getGradeId())).getName());*/
                        sec3.setStName("第" + (k + 1) + "节");
                        sec3.setScNum(k+1);
                        sec3.setStStartTime(stStartArr[k]);
                        sec3.setStEndTime(stEndArr[k]);
                        sec3.setDeleted(0);
                        secList.add(sec3);
                    }
                }
            }

            ptSectionUnionService.insertBatch(secList);
            Date endTime = new Date();
            PtSectionUnion sectionUnion1 = new PtSectionUnion();
            sectionUnion1.setOrgId(ptSectionUnion.getOrgId());
            SectionUnionMessageVo secu = new SectionUnionMessageVo(MessageTypes.SECTIONUNION_UPDATE.name(),sectionUnion1,beginTime,endTime);
            jmsService.sendMessage(secu);
            result.setCode(Result.SUCCESS);
            result.setMsg("操作成功");


        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
            logger.info("操作失败",e);
        }
        return result;
    }

    /**
     * 删除节次管理
     */
    @RequestMapping(value = "/delete/{id}")
    @ResponseBody
    public Result delete(@PathVariable String id) {
        Result result = new Result();
        try {
            if(StringUtils.isNotBlank(id)){
                PtSectionCategory sc=ptSectionCategoryService.selectById(id);
                sc.setDeleted(1);
                ptSectionCategoryService.updateById(sc);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                Date start = dateFormat.parse(dateFormat.format(date));
                ptSectionUnionService.updateDelflagByName(sc.getName());
                ptSectionTimeService.deleteByScId(id);
                PtSectionUnion sectionUnion1 = new PtSectionUnion();
                sectionUnion1.setCreateTime(start);
                SectionUnionMessageVo secu = new SectionUnionMessageVo(MessageTypes.SECTIONUNION_DELETE.name(),sectionUnion1);
                jmsService.sendMessage(secu);
                result.setMsg("操作成功");
                result.setCode(Result.SUCCESS);
            }
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
            logger.error("操作失败",e);
        }
        return result;
    }

    /**
     * 修改节次管理
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Result update(PtSectionUnion ptSectionUnion,Integer sections) {
        Result result = new Result();
        try {
            //保存之前先验证时间有无重叠
            EntityWrapper<PtSectionCategory> wrapper = new EntityWrapper<>();
            wrapper.eq("org_id",ptSectionUnion.getOrgId());
            wrapper.eq("deleted",0);
            List<PtSectionCategory> all = ptSectionCategoryService.selectList(wrapper);
            for (PtSectionCategory section:all
            ) {
                if(section.getId().equals(ptSectionUnion.getId())) {
                    continue;
                }
                //如果新保存得节次得开始时间在之前已有节次得开始结束时间之内,
                //或新保存得节次得结束时间在之前已有节次得开始结束时间之内
                if(((ptSectionUnion.getStartTime().compareTo(section.getStartTime()))!=1
                        && (ptSectionUnion.getEndTime().compareTo(section.getStartTime()))==1)
                        || ((ptSectionUnion.getStartTime().compareTo(section.getEndTime()))!=1
                        && (ptSectionUnion.getEndTime().compareTo(section.getEndTime()))==1 )){

                    result.setCode(Result.FAIL);
                    result.setMsg("与已有节次得应用时间重叠");
                    return result;
                }
            }

            String orgId = ptSectionUnion.getOrgId();
            /*SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");*/
            Date beginTime = new Date();
           // ptSectionUnion.setLastupDttm(new Date());
            /*String[] gradeArr = new String[0];*/
            String[] weekArr = new String[0];
            String[] stStartArr = new String[0];
            String[] stEndArr = new String[0];
            String stStartTime = ptSectionUnion.getStStartTime();
            String stEndTime = ptSectionUnion.getStEndTime();
            if (StringUtils.isNotBlank(stStartTime) && StringUtils.isNotBlank(stEndTime)) {
                stStartArr = stStartTime.split(",");
                stEndArr = stEndTime.split(",");
                //根据开始时间给数组进行排序·
                Arrays.sort(stStartArr);
                Arrays.sort(stEndArr);
            }

            //先清空细节表
            ptSectionUnionService.deleteByCategoryId(ptSectionUnion.getId());
            ArrayList<PtSectionUnion> secList = new ArrayList<>();
            if (StringUtils.isNotBlank(ptSectionUnion.getOrgId())) {
                PtOrg org = orgService.selectById(ptSectionUnion.getOrgId());
                ptSectionUnion.setOrgName(org.getName());
                String termName = MetaUtils.getMeta(Integer.valueOf(ptSectionUnion.getTermId())).getName();
                ptSectionUnion.setTermName(termName);

                if (StringUtils.isNotBlank(ptSectionUnion.getWeek())) {
                    weekArr = ptSectionUnion.getWeek().split(",");

                    for (int j = 0; j < weekArr.length; j++) {
                        PtSectionUnion sec2 = new PtSectionUnion();
                        BeanUtils.copyProperties(ptSectionUnion, sec2, "id");
                        sec2.setWeek(weekArr[j]);
                        for (int k = 0; k < stStartArr.length; k++) {
                            PtSectionUnion sec3 = new PtSectionUnion();
                            BeanUtils.copyProperties(sec2, sec3, "id");
                            sec3.setCategoryId(ptSectionUnion.getId());
                            sec3.setStName("第" + (k + 1) + "节");
                            sec3.setScNum(k+1);
                            sec3.setStStartTime(stStartArr[k]);
                            sec3.setStEndTime(stEndArr[k]);
                            secList.add(sec3);
                        }
                    }

                }


            }

            ptSectionUnionService.insertBatch(secList);
            Date endTime = new Date();
            PtSectionUnion sectionUnion1 = new PtSectionUnion();
            sectionUnion1.setOrgId(ptSectionUnion.getOrgId());
            SectionUnionMessageVo secu = new SectionUnionMessageVo(MessageTypes.SECTIONUNION_UPDATE.name(),sectionUnion1,beginTime,endTime);
            jmsService.sendMessage(secu);

            PtSectionCategory sc = new PtSectionCategory();
            BeanUtils.copyProperties(ptSectionUnion, sc);
            sc.setLastupDttm(new Date());
            /*String gradeId = sc.getGradeId();
            String[] split = gradeId.split(",");
            StringBuilder GradeName = new StringBuilder();
            for (int i = 0; i <split.length ; i++) {
                if(i==0){
                    GradeName.append(MetaUtils.getMeta(Integer.valueOf(split[i])).getName());
                }else {
                    GradeName.append("," + MetaUtils.getMeta(Integer.valueOf(split[i])).getName());
                }
            }
            sc.setGradeName(GradeName.toString());*/
            sc.setCreator(ShiroKit.getUser().getId());
            sc.setSections(sections);
            ptSectionCategoryService.updateById(sc);
            ptSectionTimeService.deleteByScId(sc.getId());
            ArrayList<PtSectionTime> stList = new ArrayList<>();
            for (int i = 0; i < stStartArr.length; i++) {
                PtSectionTime st = new PtSectionTime();
                BeanUtils.copyProperties(ptSectionUnion, st);
                st.setId(null);
                st.setName("第" + (i + 1) + "节");
                st.setSection(i + 1);
                st.setStartTime(stStartArr[i]);
                st.setEndTime(stEndArr[i]);
                st.setSectionCategoryId(sc.getId());
                st.setCreateTime(new Date());
                stList.add(st);

            }
            ptSectionTimeService.insertBatch(stList);

            result.setMsg("操作成功");
           result.setCode(Result.SUCCESS);
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
            logger.error("操作失败",e);
        }
        return result;
    }

    /**
     * 节次管理详情
     */
    @RequestMapping(value = "/detail/{ptSectionCategoryId}")
    @ResponseBody
    public Object detail(@PathVariable("ptSectionCategoryId") Integer ptSectionCategoryId) {
        return ptSectionCategoryService.selectById(ptSectionCategoryId);
    }


    @RequestMapping("/disableSection/{id}/{enable}")
    @ResponseBody
    public Result disableSection(@PathVariable String id,@PathVariable Integer enable){
        Result result = new Result();
        try {
            if (StringUtils.isNotBlank(id)){
                PtSectionCategory sc = ptSectionCategoryService.selectById(id);
                sc.setId(id);
                sc.setEnable(enable);
                ptSectionCategoryService.updateById(sc);
                PtSectionCategory s = ptSectionCategoryService.selectById(id);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date();
                Date start = dateFormat.parse(dateFormat.format(date));
                ptSectionUnionService.disableByName(enable,s.getName());
                PtSectionUnion sectionUnion1 = new PtSectionUnion();
                sectionUnion1.setCreateTime(start);
                SectionUnionMessageVo secu = new SectionUnionMessageVo(MessageTypes.SECTIONUNION_UPDATE.name(),sectionUnion1);
                jmsService.sendMessage(secu);
                if (enable==1){
                    result.setMsg("启用成功");
                }else {
                    result.setMsg("禁用成功");
                }

                result.setCode(Result.SUCCESS);
            }
        } catch (Exception e) {
            result.setMsg("操作失败");
            result.setCode(Result.FAIL);
            logger.error("操作失败",e);
        }
        return result;
    }
}
